package com.hax.config;

import com.hax.constants.SecurityConstants;
import com.hax.security.CustomLogoutHandler;
import com.hax.security.CustomPasswordEncoder;
import com.hax.security.CustomProvider;
import com.hax.security.filter.CustomLoginUsernamePasswordFilter;
import com.hax.security.filter.CustomRequestUsernamePasswordFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private CustomProvider customProvider;

    @Bean
    public PasswordEncoder passwordEncoder() {
        //自定义密码加解密
        return new CustomPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭csrf
        http.csrf().disable()
                .anonymous().disable()
                // 禁用session
                .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                //添加provider
                .authenticationProvider(customProvider)
                .authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> {
                    authorizationManagerRequestMatcherRegistry.antMatchers(SecurityConstants.LOGIN_URL).permitAll();
                    authorizationManagerRequestMatcherRegistry.antMatchers(SecurityConstants.LOGOUT_URL).permitAll();
                    authorizationManagerRequestMatcherRegistry.anyRequest().authenticated();
                    //可配置其他的静态访问资源
                })
                //添加登录拦截器
                .addFilterAt(new CustomLoginUsernamePasswordFilter(customProvider), UsernamePasswordAuthenticationFilter.class)
                //在CustomLoginUsernamePasswordFilter之前去执行
                .addFilterBefore(new CustomRequestUsernamePasswordFilter(), CustomLoginUsernamePasswordFilter.class)
                //退出登录
                .logout().logoutUrl(SecurityConstants.LOGOUT_URL).addLogoutHandler(new CustomLogoutHandler());
    }

}
